﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using IFWiki.Utils;

namespace IFWiki.Models
{
    public partial class Article : IRevisable
    {
        /// <summary>
        /// The name (i.e. Title) of the article. Can contain spaces and other characters        
        /// </summary>
        /// <value>The name.</value>
        public string Name { get; set; }

        /// <summary>
        /// Markdown body of the article itself.
        /// </summary>
        public string Detail { get; set; }

        /// <summary>
        /// Reason for the last revision.
        /// </summary>
        public string Reason { get; set; }

        /// <summary>
        /// Date/Time at which this revision was created
        /// </summary>
        /// <value>The revised at.</value>
        public DateTime RevisedAt { get; set; }

        public string RevisedBy { get; set; }

        public bool IsDiscussion
        {
            get
            {
                return this.Name.StartsWith("Talk on ");
            }
        }

        public string InnerType { get { return "Article"; } }

    }

    public partial class Article
    {
        public Article()
        {
            //parameterless, for serialization
        }
        public Article(string name)
        {
            this.Name = name;

            if (name != null)
            {
                var savedArticle = (Article)Persister.Load(this.Name, this.GetType()) ?? Defaults.GetArticle(name);
                this.Name = savedArticle.Name;
                this.Detail = savedArticle.Detail;
            }
        }

        public void Save(string reason, string revisedBy)
        {
            this.Reason = reason;
            this.RevisedAt = DateTime.Now;
            this.RevisedBy = revisedBy;
            Debug.Assert(!string.IsNullOrEmpty(this.Name));
            Persister.Save(this.Name, this, this.RevisedAt);            
        }

        //TODO: All the revision stuff should be extension to the IRevisable.

        public List<IRevisable> LoadRevisions()
        {
            var revisions = new List<IRevisable>();
            revisions = Persister.LoadList<IRevisable>(this.Name, typeof(Article)); // ?? Defaults.GetArticle(name);
            return revisions;
        }

        internal static Article Revert(string name, DateTime revisedAt, string revertedBy)
        {
            var article = LoadRevision(name, revisedAt);
            article.Save("revert from " + revisedAt.ToString(), revertedBy);
            return article;
        }

        internal static Article LoadRevision(string name, DateTime revisedAt)
        {
            return Persister.LoadRevision<Article>(name, revisedAt, typeof(Article));
        }
    }
}
